# encoding=utf-8
import requests
import json


class wenshu(object):
    def __init__(self):
        self.session = requests.session()
        self.session.get('https://anli.court.gov.cn/static/web/index.html')
        self.header = {
            "Content-Type": 'application/json;charset=UTF-8',
            "User-Agent": 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.25 Safari/537.36 Core/1.70.3880.400 QQBrowser/10.8.4554.400',
            "Accept-Language": 'zh-CN,zh;q=0.9',
            "Accept": 'application/json, text/plain, */*',
            "Accept-Encoding": 'gzip, deflate, br',
            "Referer": 'https://anli.court.gov.cn/static/web/index.html',
            "Host": 'anli.court.gov.cn',
            "Origin": 'https://anli.court.gov.cn',
        }

    def getAnliIDs(self, num):
        payload = {
            'advs': [{'bmfName': "刑法"}, {'bmfName': "刑法"}, {'aydm': "1:1", 'ayName': "刑事案由"}],
            'from': 0,
            'limit': "%s" % num,
            'pxf': 1,
            'query': [],
            'sort': 0,
        }
        jdata = json.dumps(payload)
        response = self.session.post('https://anli.court.gov.cn/sfalw/search/alk/aljs/search', headers=self.header,
                                     data=jdata)
        json_value = json.loads(response.text)
        resultList = json_value['data']['dataItem']['resultList']
        ids = []
        for result in resultList:
            ids.append(result['id'])
        print(ids)
        return ids

    def getAnlis(self, num):
        ids = self.getAnliIDs(num)
        texts = []
        dataItems = []
        for id in ids:
            url = 'https://anli.court.gov.cn/sfalw/case/altx/cases/detail/' + id
            getResponse = self.session.get(url, headers=self.header)
            value = json.loads(getResponse.text)
            dataItems.append(value['data']['dataItem'])

        for dataItem in dataItems:
            ajzw = dataItem['ajzw']  # 案情
            jbaq = dataItem['jbaq']
            if ajzw is not None:
                text = ajzw
            else:
                text = jbaq
            texts.append(text)
        return texts

    def saveAnlis(self, num):
        texts = self.getAnlis(num)
        for i in range(int(num)):
            tempNum = i+1
            jsonpath = 'cases/spiderCases' + str(tempNum) + '.txt'
            with open(jsonpath, 'w') as file:
                file.write(texts[i])
                file.write('\n')


if __name__ == '__main__':
    demo = wenshu()
    demo.saveAnlis(10)
